package com.lp.rpc.registry;
import com.lp.rpc.constants.LpConstant;
import com.lp.rpc.registry.watcher.NodeDataChangeWatcher;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务发现
 *
 * @author steakLiu
 */
public class ZkServiceDiscovery implements ApplicationContextAware, InitializingBean {

    private String zkAddress;

    public ZkServiceDiscovery(String zkAddress) {
        this.zkAddress = zkAddress;
    }

    private final Map<String,Object> map = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        List<String> children = ZkOperation.getChildren(LpConstant.ServiceRoot, new NodeDataChangeWatcher());
        /**
         *
         *
         * 存服务键值表，key接口名 ， value为服务接口路劲 ，客户端发起调用的时候，将注册中心匹配的接口路径传到服务端进行反射调用
         *
         *
         */
        for (String child : children) {
            String data = ZkOperation.getData(LpConstant.ServiceRoot+ "/" + child);
            map.put(child, data);
        }
    }


    public void afterPropertiesSet() throws Exception {
        /**
         *
         * 将服务注册列表放在本地缓存起来，防止频繁访问zk带来的压力
         *
         */
        LocalServiceCache.putBatch(map);
    }

}
